package cn.ilikes.tools.hbase.jpa.persistences.context.operations;

import java.util.LinkedList;
import java.util.Queue;

import cn.ilikes.tools.hbase.jpa.clients.Client;
import cn.ilikes.tools.hbase.jpa.clients.JPAHBaseClientsException;
import cn.ilikes.tools.hbase.jpa.clients.nodes.INodeBuilderListener;
import cn.ilikes.tools.hbase.jpa.clients.nodes.INodeGraphBuilder;
import cn.ilikes.tools.hbase.jpa.clients.nodes.Node;
import cn.ilikes.tools.hbase.jpa.clients.nodes.NodeGraphBuilder;
import cn.ilikes.tools.hbase.jpa.clients.nodes.NodeLifeCycle.LifeCycle;
import cn.ilikes.tools.hbase.jpa.metadatas.IEntityMetaData;
import cn.ilikes.tools.hbase.jpa.persistences.context.AbstractContext;
import cn.ilikes.tools.hbase.jpa.persistences.context.Operation;
import cn.ilikes.tools.hbase.jpa.persistences.context.OperationRunTimeException;

public class RemoveOperation extends ContextOperation implements Operation<Boolean> {

	private Object entity;

	private Queue<Node> stack = new LinkedList<Node>();

	public RemoveOperation(OperationType operationType, AbstractContext context, Object entity) {
		super(operationType, context);
		this.entity = entity;

	}

	@Override
	public Boolean exec() {

		Client client = getContext().getClient();
		try {
			while (!stack.isEmpty()) {
				client.delete(stack.poll());
			}
			return Boolean.TRUE;
		} catch (JPAHBaseClientsException e) {
			throw new OperationRunTimeException(e);
		}
	}

	@Override
	public boolean flush() {

		return true;
	}

	@Override
	public boolean rollback() {

		return true;
	}

	@Override
	public boolean initSub(AbstractContext context) {

		INodeGraphBuilder nodeGraphBuilder = new NodeGraphBuilder(context.getHbasePersistenUnitEnv(), new INodeBuilderListener() {
			@Override
			public void buildNode(Node node) {

				stack.add(node);
			}
		});
		IEntityMetaData entityMetaData = context.getHbasePersistenUnitEnv().getEntityMetaDataFactory().selectIEntityMetaData(entity.getClass());
		//		Node node = new Node(entityMetaData, entity);
		Node node = Node.createtNode(entityMetaData, entity, LifeCycle.newses);
		nodeGraphBuilder.buildNodeStack(node);
		return true;
	}

}
